package data.join.com.utils;

import android.content.Context;
import android.os.PowerManager;

import java.util.HashMap;

import data.join.com.media.AppUpdateThread;

/**
 * Created by Administrator on 2016/5/11.
 */
public class WakeLockUtils {
    public final static String TAG = "WakeLockUtils";
    private Context mContext;
    private static WakeLockUtils mWakeLockUtils;
    HashMap<String,PowerManager.WakeLock> mWakeLockMap = new HashMap<String,PowerManager.WakeLock>();

    private WakeLockUtils(Context c){
        mContext = c;
    }

    public static synchronized WakeLockUtils getDefault(Context c){
        if(mWakeLockUtils == null){
            mWakeLockUtils = new WakeLockUtils(c);
        }
        return mWakeLockUtils;
    }

    public void acquireWakeLock(String tag){
        acquireWakeLock(tag,-1);
    }
    public void acquireWakeLock(String tag, int time){
        PowerManager.WakeLock lock = getWakeLockByTag(tag);
        if(time > 0)
            lock.acquire(time);
        else
            lock.acquire();
        MyLog.D(TAG,"acquireWakeLock tag="+tag);
    }
    public void releaseWakeLock(String tag){
        PowerManager.WakeLock lock = mWakeLockMap.get(tag);
        if(lock != null) {
            lock.release();
            MyLog.D(TAG,"releaseWakeLock tag="+tag);
        }else {
            //MyLog.E(TAG,"releaseWakeLock Fail,lock is NULL, tag=" + tag);
        }
    }

    private PowerManager.WakeLock getWakeLockByTag(String tag){
        PowerManager.WakeLock lock =  mWakeLockMap.get(tag);
        if(lock == null){
            if(AppUpdateThread.INSTALL_LOCK_TAG.equals(tag)){
                lock = newWakeUpLock(tag);
            }else{
                lock = newWakeLock(tag);
            }
            mWakeLockMap.put(tag,lock);
        }
        return lock;
    }


    private PowerManager.WakeLock newWakeLock(String tag) {
        PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,tag);
        mWakeLock.setReferenceCounted(false);
        return mWakeLock;
    }

    private PowerManager.WakeLock newWakeUpLock(String tag) {
        PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK|PowerManager.ACQUIRE_CAUSES_WAKEUP,tag);
        mWakeLock.setReferenceCounted(false);
        return mWakeLock;
    }
}
